package cc.ok200.muzhi;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowInsetsController;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final String API_URL = "http://192.168.0.189:8081/user/device/login";
    
    private EditText etMobile;
    private EditText etPassword;
    private Button btnLogin;
    private ProgressBar progressBar;
    
    // 添加一个标志变量，表示当前是否正在登录
    private boolean isLoggingIn = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        
        // 设置沉浸式状态栏
        setImmersiveStatusBar();
        
        setContentView(R.layout.activity_login);
        
        // 初始化Storage
        Storage.init(getApplicationContext());
        
        // 初始化视图
        etMobile = findViewById(R.id.et_mobile);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        progressBar = findViewById(R.id.progress_bar);
        
        // 初始化标题栏按钮
        ImageButton btnClose = findViewById(R.id.btn_close);
        ImageButton btnBook = findViewById(R.id.btn_book);
        
        // 设置叉子图标点击事件（关闭页面）
        if (btnClose != null) {
            btnClose.setOnClickListener(v -> finish());
        }
        
        // 设置书本图标点击事件（暂不做操作）
        if (btnBook != null) {
            btnBook.setOnClickListener(v -> {
                // 目前暂不做操作，可以显示一个提示
                Toast.makeText(LoginActivity.this, "帮助功能开发中", Toast.LENGTH_SHORT).show();
            });
        }
        
        // 设置登录按钮点击事件
        btnLogin.setOnClickListener(v -> {
            // 避免重复点击
            if (!isLoggingIn) {
                login();
            }
        });
        
        // 请求权限
        requestStoragePermission();
    }
    
    /**
     * 设置沉浸式状态栏，使应用内容延伸到状态栏
     */
    private void setImmersiveStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 设置状态栏透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.antd_blue));
            
            // 设置状态栏图标为白色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    
    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10 (Q) 及以上版本，应用可以直接访问自己的应用专属目录
                // 无需额外请求存储权限
                checkLocalToken();
            } else {
                // Android 6.0 (M) 到 Android 9.0 (P)，需要请求存储权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            PERMISSION_REQUEST_CODE);
                } else {
                    // 已有权限，检查本地token
                    checkLocalToken();
                }
            }
        } else {
            // 6.0以下系统，直接检查本地token
            checkLocalToken();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            // 只有在Android 9.0及以下版本才会走到这里
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，检查本地token
                checkLocalToken();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "未获得存储权限", Toast.LENGTH_SHORT).show();
                // Android 10及以上版本不应显示此信息
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    finish();
                } else {
                    checkLocalToken();
                }
            }
        }
    }
    
    private void checkLocalToken() {
        String token = Storage.read(".token", null);
        if (token != null && !token.isEmpty()) {
            // Token存在，直接跳转到MainActivity
            startMainActivity();
        } else {
            // 读取上次保存的账号和密码
            String savedMobile = Storage.read(".mobile", null);
            String savedPassword = Storage.read(".password", null);
            
            // 如果账号和密码存在，则填充到输入框中
            if (savedMobile != null && !savedMobile.isEmpty()) {
                etMobile.setText(savedMobile);
            }
            
            if (savedPassword != null && !savedPassword.isEmpty()) {
                etPassword.setText(savedPassword);
                // 将光标定位到末尾
                etPassword.setSelection(savedPassword.length());
            } else if (savedMobile != null && !savedMobile.isEmpty()) {
                // 如果只有账号，没有密码，则将光标定位到密码输入框
                etPassword.requestFocus();
            }
        }
    }
    
    private void login() {
        String mobile = etMobile.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        
        if (mobile.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示加载中
        setLoading(true);
        
        // 构建请求参数
        JSONObject requestData = new JSONObject();
        try {
            // 获取屏幕真实物理尺寸
            android.util.DisplayMetrics displayMetrics = new android.util.DisplayMetrics();
            getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
            int realWidth = displayMetrics.widthPixels;
            int realHeight = displayMetrics.heightPixels;
            
            requestData.put("mobile", mobile);
            requestData.put("password", password);
            requestData.put("uuid", getDeviceUUID());
            requestData.put("name", Build.MODEL);
            requestData.put("width", realWidth);
            requestData.put("height", realHeight);
            requestData.put("brand", Build.BRAND);
            requestData.put("model", Build.MODEL);
            requestData.put("osVersion", Build.VERSION.SDK_INT);
        } catch (JSONException e) {
            Log.e(TAG, "构建JSON数据失败", e);
            Toast.makeText(this, "登录失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            setLoading(false);
            return;
        }
        
        // 发送登录请求
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestData.toString());
        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Log.e(TAG, "网络请求失败", e);
                    Toast.makeText(LoginActivity.this, "网络连接失败，请检查网络", Toast.LENGTH_SHORT).show();
                    setLoading(false);
                });
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Log.e(TAG, "服务器响应错误: " + response.code());
                        Toast.makeText(LoginActivity.this, "服务器错误: " + response.code(), Toast.LENGTH_SHORT).show();
                        setLoading(false);
                    });
                    return;
                }
                
                try {
                    String responseString = response.body().string();
                    JSONObject jsonResponse = new JSONObject(responseString);
                    
                    if (jsonResponse.has("code")) {
                        // 登录失败
                        String errorMsg = jsonResponse.optString("msg", "登录失败");
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            setLoading(false);
                        });
                    } else {
                        // 登录成功
                        JSONObject data = jsonResponse.getJSONObject("data");
                        String token = data.getString("token");
                        
                        // 保存token到本地
                        Storage.write(".token", token);
                        Storage.write(".mobile", mobile);
                        Storage.write(".password", password);
                        
                        // 跳转到主界面
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            startMainActivity();
                        });
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> {
                        Log.e(TAG, "处理响应数据失败", e);
                        Toast.makeText(LoginActivity.this, "登录失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        setLoading(false);
                    });
                }
            }
        });
    }
    
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
    
    private void setLoading(boolean isLoading) {
        progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        isLoggingIn = isLoading; // 更新登录状态标志
        
        if (isLoading) {
            // 登录中状态：浅蓝色背景
            btnLogin.setBackground(getResources().getDrawable(R.drawable.rounded_button_bg_disabled));
            btnLogin.setText("登录中...");
            // 不再设置setEnabled(false)，保持按钮视觉效果
        } else {
            // 正常状态：恢复原背景和文字
            btnLogin.setBackground(getResources().getDrawable(R.drawable.rounded_button_bg));
            btnLogin.setText("登 录");
        }
    }
    
    private String getDeviceUUID() {
        String uuid = Storage.read(".uuid", null);
        if (uuid == null || uuid.isEmpty()) {
            uuid = UUID.randomUUID().toString().replace("-", "");
            Storage.write(".uuid", uuid);
        }
        return uuid;
    }
} 